<template>
  <div class="cs-container">
    <div class="cs-title clear">
      <div class="left">视频</div>
      <div class="right"></div>
    </div>
    <div class="cs-content cs-table">
      <div class="form-tool">
        <el-form :inline="true" :model="form" size="mini">
          <el-form-item label="">
            <el-upload
            ref="upload"
              :show-file-list="false"
              multiple
              :limit="limit"
              :on-exceed="handleExceed"
              class="upload-demo"
              action="/springBoot/file-service/io/upload"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="" v-show="false">
            <el-input v-model="form.name" placeholder="请输入IP" :disabled="true"/>
          </el-form-item>
          <!-- <el-form-item label="">
            <el-select v-model="form.region" placeholder="请选择分组">
              <el-option label="区域一" value="shanghai">111</el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="form.region" placeholder="请选择">
              <el-option label="区域一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="">
            <el-checkbox v-model="form.is_delete" @change="($event) => handle('is_delete', $event)">显示已删除文件</el-checkbox>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" size="mini" @click="query">查询</el-button>
            <el-button size="mini" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="data-table" >
        <div class="data-page"
					v-loading="loading"
					:element-loading-text="loadingText"
					element-loading-spinner="el-icon-loading"
					element-loading-background="rgba(0, 0, 0, 0.6)"> 
					<div class="img-box" v-for="(item, index) in tableData" :key="index"
						:class="item.is_delete == -1 ? 'error' : ''" :title="item.file_name">
						<template v-if="fileTypeList.includes(item.file_type.substring(1))">
							<el-image 
								:key="index"
								:src="item.url_thumbnail" 
								:lazy="true"
								:preview-src-list="SELECT_IOList(index)">
							</el-image>
						</template>
						<template v-else>
							<el-image 
								:src="require('./../../../assets/images/download.png')" >
							</el-image>
						</template>
						
						<div class="error" v-if="item.is_delete == -1">已删除</div>
						<div class="error" v-if="item.ip == '127.0.0.1'" :class="item.is_delete == 0 ? 'dev' : 'dev-delete'">开发环境</div>
						<div class="tool">
							<i class="el-icon-picture-outline" title="原图预览" @click="handle('preview', item)"></i>
							<i class="el-icon-download" title="原图下载" @click="handle('download', item)"></i>
							<i class="el-icon-delete" v-if="item.is_delete == 0" title="删除" @click="handle('delete', item)"></i>
							<i class="el-icon-refresh-left" v-if="item.is_delete == -1" title="撤销删除" @click="handle('revokeDelete', item)"></i>
						</div>

						<div class="info">
							<div>名称：{{item.name}}</div>
							<div>大小：{{item.file_size}}</div>
							<div>{{item.create_time}}</div>
						</div>
					</div>
				</div>

        <!-- 分页 -->
        <div class="cs-pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.current"
            :page-sizes="page.pageSizes"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
          ></el-pagination>
        </div>
      </div>
    </div>

    <!-- modal -->
  </div>
</template>

<script>
// import { SELECT_IO, DELETE_IO, REVOKE_DELETE_IO } from '@/plugins/api/common'
const getFile = {};
export default {
  name: "ui",
  data() {
    return {
      form: {
        is_delete: false
      },
      tableData: [],
      loading: false,
			loadingText: 'Loading...',
      page: {
        current: 1,
        pageSizes: [10, 20, 30, 40, 50, 100],
        pageSize: 40,
        total: 0
      },
      srcList: [],
      fileTypeList: ['mp4', 'jpg', 'jpeg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'ico', 'jfif'],
      dialog: {
        visible: false,
      },
      limit: 9,
      selectedNum: 0,
      uploadedNum: 1
    };
	},
	computed: {
	},
  mounted() {
    this.loadData();
  },
  methods: {
    SELECT_IOList(index) {
        let arr = []
        let i = 0;
      for(i;i < this.srcList.length;i++){
        arr.push(this.srcList[i+index])
        if(i+index >= this.srcList.length-1){
          index = 0-(i+1);
        }
      }
      return arr;
    },
    async handle (type, obj) {
      if (type === 'preview') {
        window.open(obj.url);
      }
      if (type === 'download') {
        window.open(obj.url + '?type=d');
      }
      if (type === 'is_delete') {
        this.page.current = 1;
        this.is_delete = obj;
        this.loadData();
      }
      if (type === 'revokeDelete') {
        const res = await REVOKE_DELETE_IO({id: obj.id});
        if (res.status) {
          this.$message({
            type: 'success',
            message: '撤销成功!'
          });
          this.loadData();
        } else {
          this.$message({
            type: 'error',
            message: res.messages || '撤销失败!'
          });
        }
        this.loadData();
      }
      if (type === 'delete') {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          DELETE_IO({id: obj.id}).then(res => {
            if (res.status) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.loadData();
            } else {
              this.$message({
                type: 'error',
                message: res.messages || '删除失败!'
              });
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },

    formatFileSize(bytes) {
      var result = null;
      bytes = +bytes;
      if (bytes === 0) return '0 B';
      
      var k = 1024;
      
      const sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      
      let i = Math.floor(Math.log(bytes) / Math.log(k));

      var num = bytes / Math.pow(k, i);
      return num.toPrecision(3) + ' ' + sizes[i];
      
      //return (bytes / Math.pow(k, i)) + ' ' + sizes[i]; 
      //toPrecision(3) 后面保留一位小数，如1.0GB //return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
      return result;
    },

    /**
     * 查询
     */
    query() {
      this.page.current = 1;
      this.loadData();
    },

    /**
     * 重置
     */
    reset() {
      this.form.is_delete = false;
      this.loadData();
    },

    // 查看
    preview(map) {
      this.$utils.el.alert(map.userAgent);
    },

    /**
     * 加载数据
     */
    loadData() {
      this.loading = true;
			this.loadingText = 'Loading...';
      SELECT_IO({
        needPage: true,
        current: this.page.current,
        pageSize: this.page.pageSize,
        label: 'video',

        queryData: {
          name: 333,
          age: undefined
        },
      }).then(response => {
        this.loading = false;
        this.srcList = [];
        response.data.rows.forEach(item => {
          this.srcList.push(item.url_preview);
          item.file_size = this.formatFileSize(item.file_size_thumbnail);
        });
        this.tableData = response.data.rows;


        this.page.total = response.data.total;
      });
    },

    /**
     * 每页多少条
     */
    handleSizeChange(val) {
      this.page.current = 1;
      this.page.pageSize = val;
      this.loadData();
    },

    /**
     * 下一页
     */
    handleCurrentChange(val) {
      this.page.current = val;
      this.loadData();
    },
    handleExceed(files, fileList) {
      alert(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件`);
      this.$refs.upload.clearFiles();
    },  
    handleAvatarSuccess(res, file) {
      this.uploadedNum++;
			this.loading = false;
      if (res.status) {
        this.selectedNum = 0;
        this.uploadedNum = 1;
        
        this.$refs.upload.clearFiles();

        this.page.current = 1;
        this.tableData = [];
        this.loadData();

        this.$refs.upload.clearFiles();
        alert('上传成功');
      } else {
         this.$message.success(res.messages || '上失败');
         this.$refs.upload.clearFiles();
      }
    },
    beforeAvatarUpload(file) {
      this.selectedNum++;
			this.loadingText = '正在上传，请稍后。。。';
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 50;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        alert('上传文件大小不能超过 50MB!');
      }
			
			this.loading = isLt2M ? true : false;
      return isLt2M;
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="less" scoped>
	.data-page {
		padding-left: 10px;
		height: calc(100% - 60px);
		border-bottom: 1px solid #CFD5DE;
		overflow: auto;
		padding-bottom: 10px;
	}
	/deep/ .el-icon-loading {
		font-size: 32px;
	}
  .img-box {
    position: relative;
    // display: inline-flex;
		// align-items: baseline;
    display: inline-block;
		overflow: hidden;
		width: 150px;
		height: 150px;
		margin: 10px 10px 0 0;
		border-radius: 0;
		box-shadow: 0 0 8px #eeeeee;
		.el-image {
			width: 150px;
      height: 100%;
		}
    &.error {
      .el-image {
        border: 2px solid red !important;
				border-radius: 5px;
      }
    }
    .error {
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(255, 0, 0, .7);
      color: white;
      padding: 2px 5px;
      border-top-left-radius: 5px;
      &.dev {
        top: 0;
        background: blue;
        .el-image {
          border-color: blue;
        }
      }
      &.dev-delete {
        top: 25px;
        background: blue;
      }
    }
    .tool {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 15px;
      background: black;
      opacity: 0;
      color: white;
      padding: 2.5px 5px;
			transform: translateY(-10px);
      transition-duration: .5s;
      i {
        cursor: pointer;
        padding: 0 2px;
        &:hover {
          color: red;
        }
      }
    }
    .info {
      opacity: 0;
      position: absolute;
      bottom: 0;
      left: 0;
      background: rgba(0, 0, 0, .7);
      color: white;
			font-size: 12px;
      padding: 2.5px 5px 5px 5px;
      width: calc(100%);
      transition-duration: .5s;
      transform: translateY(10px);
      div {
        padding-top: 2.5px;
      }
    }

    &:hover {
			background: #E5F3FF;
      .tool {
        opacity: 1;
				transform: translateY(0);
        transition-duration: .5s;
      }
      .info {
        opacity: 1;
        transform: translateY(0);
        transition-duration: .5s;
      }
    }
  }
</style>